const Actions = require('./actions');
const DB = require('app/db');
import { monStorage, Storage } from 'clientConfig/util/StoreData';
import { guid, getTime, getMarkdownText, sendNotice,dealTime } from 'clientConfig/util/queryurlfield';
import { Control } from 'react-keeper';
import { NEW, RUNNING } from 'clientConfig/constants'
const { Toast } = SaltUI;

module.exports = Reflux.createStore({
    listenables: [Actions],
    data: {

    },
    onFetch: function (parama, cb) {
        let t = this;
        DB.Approval.get_approval_list({
            module_type: "tender",
            proj_category: "tenderplan",
            status: 8,
            PageNum: 0,
            CountForAPage: 100,
            id: Storage.get('user.id')
        })
            .then((content) => { // 成功
                var proNumAll = [];
                var proNameAll = [];
                var webhookAll = [];
                var pro_info = null;
                if (content.list instanceof Array) {
                    content.list.map((item, index) => {
                        try {
                            pro_info = JSON.parse(item.pro_info);
                        } catch (e) {
                            pro_info = item.pro_info;
                        }
                        var obj = {}
                        obj.value = index;
                        obj.text = item.proj_name;
                        obj.annual = pro_info && pro_info["annual"];
                        obj.special = pro_info && pro_info['special'];
                        obj.budget = pro_info && pro_info['budget'];
                        obj.folder_id = item['folder_id'];
                        proNameAll.push(obj);
                        proNumAll.push(item.proj_num);
                    })
                }
                t.data.proNumAll = proNumAll
                t.data.proNameAll = proNameAll

                t.updateComponent();
            })
            .catch((error) => { // 失败 or 有异常被捕获

            });
    },
    onSubmit: function (params, cb) {
        let t = this;
        let required_params = this.fit(params);
        let notice_info = {
            "process_id": required_params.process_id,
            "proj_num": required_params.proj_num,
            "proj_name": required_params.proj_name,
            "create_time": required_params.create_time,
            "status": required_params.status,
            "type": params.pagedata ? "变更申请" : "待我审批的"
        }
        let noticed_lists = required_params.approvers_id[required_params.next_cursor];
        if (params.pagedata) {
            required_params = this.modify(required_params, params);
            // debugger
        }
        DB.Approval.send_approval(required_params)
            .then((content) => {
                if (!content) {
                    Toast.show({
                        type: 'success',
                        content: params.edit ? '你的变更申请已提交' : '你的合同签订申请已提交'
                    });
                    sendNotice(noticed_lists, notice_info)
                    Control.go(-1)
                }
            })
            .catch((error) => {
                if (error.errcode == 2) {
                    Toast.show({
                        type: 'error',
                        content: "合同签订申请正在审核中"
                    });
                }
            });
    },
    fit: function (params) {
        let agent_id = Storage.get('user.agentid');
        let create_time = getTime();
        let finish_time = "";
        let originator_user = monStorage.get('user.nickname');
        let originator_user_id = Storage.get('user.id') //审批发起人的userid
        // debugger
        let dept_id = monStorage.get('user.department');
        let approvers = params.data.approvers;
        let approvers_id = params.data.approvers_id;
        let cc_list = params.data.copyers;
        let cc_list_id = params.data.cc_list_id;
        var array = [];
        for (let i = 0; i < approvers.length; i++) {
            array.push(JSON.stringify({ content: "", file: "", imgae: "" }));
        }
        let process_result = array.length > 1 ? array : JSON.stringify({ "content": "", "file": "", "imgae": "" });
        let next_cursor = 0;
        const status = NEW;
        const module_type = "tender";
        const proj_category = "contractsign";
        const proj_num = params.data.proNum;
        const proj_name = params.data.proName.text;
        const proj_webhook = '';
        // if (Storage.get(proj_name)) {
        //     var proj_webhook = Storage.get(proj_name);
        // } else {
        //     var proj_webhook = params.proj_webhook;
        //     Storage.set(proj_name, params.proj_webhook);
        // }
        // const proj_markdown = getMarkdownText({ create_time, originator_user, approvers, proj_name, proj_num, status })
        const proj_markdown = '';
        const process_id = guid();
        let nodelists = [];
        var node_obj = {}
        let node_info = [];
        let node_name = '';
        for (let i = 0; i < params.node.length + 1; i++) {
            if (i < params.node.length) {
                var obj = {}
                obj.name = params.node[i].label;
                node_name = params.node[i].name;
                // if (node_name.includes('1')) {
                //     node_name = params.node[i].name.replace(/\d/g, '');
                // }
                // debugger
                obj.value =  params.data[node_name];
                if(params.data[node_name].hasOwnProperty('text')){
                    obj.value = params.data[node_name].text
                }       
                if (obj.name.includes("时间")) {
                    obj.value = dealTime(obj.value);
                }
            } else {
                var obj = {}
                obj.name = "上传附件";
                obj.value = JSON.stringify(params.upfileName);
            }
            node_info.push(obj);
        }
        node_obj.node_info = node_info;
        Object.assign(node_obj, { node_name: 'contractsign', modified: "0", permission: "1" });
        nodelists.push(node_obj)
        let form_component_values = {
            content: {},
            nodelists: nodelists
        }
        return Object.assign({}, { originator_user_id, agent_id, create_time, finish_time, originator_user, dept_id, approvers, approvers_id, cc_list, cc_list_id, process_result, next_cursor, status, module_type, proj_category, proj_num, proj_name, proj_webhook, process_id, form_component_values, proj_markdown })
    },
    modify: function (new_data, old_data) {
        let edit = old_data.edit;
        old_data = old_data.pagedata;
        new_data.proj_category = "changereq-tendercontractsign";
        let old_change = [];//变更前字段
        let new_change = [];//变更后字段
        // debugger
        let form_component_values_new = new_data.form_component_values;
        // let form_component_values_old = old_data.form_component_values;
        let nodelists_new = form_component_values_new.nodelists;
        // let nodelists_old = form_component_values_old.nodelists;
        let node_info_new = nodelists_new[0].node_info;
        let node_info_old = old_data.node_info;
        // for (let i = 0; i < nodelists_new.length; i++) {
        //     let node_info_new = nodelists_new[i].node_info;
        //     let node_info_old = nodelists_old[i].node_info;
        for (let j = 0; j < node_info_new.length; j++) {
            if (node_info_new[j].value != node_info_old[j].value) {
                node_info_new[j].ext_value = node_info_old[j].value//变更过
                old_change.push(node_info_old[j].value);
                new_change.push(node_info_new[j].value);
            }
        }
        // }
        form_component_values_new.nodelists = nodelists_new;
        form_component_values_new.content.changerecord_type = JSON.stringify({
            type: edit ? "撤销申请" : "内容变更",
            old_process_id: old_data.process_id,
            old_proj_category: old_data.proj_category
        })
        new_data.form_component_values = form_component_values_new;
        let { create_time, originator_user, approvers, approvers_id, next_cursor, proj_name, proj_num, status } = { ...new_data };
        new_data.proj_markdown = "";
        return new_data;
    },
    updateComponent: function () {
        this.trigger(this.data);
    }
});
